package com.newbee.fragement.multchat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.gauss.render.SpeexPlayer;
import com.gauss.render.SpeexRecorder;
import com.hhu.newbee.R;
import com.newbee.adapter.ChatMsgViewAdapter;
import com.newbee.app.OnRefrushActivity;
import com.newbee.listbean.ChatMsgBean;
import com.newbee.multchat.MultChatActivity;
import com.newbee.progressdlg.PlayProgressDlg;
import com.newbee.service.MainService;
import com.newbee.service.MainServiceKey;
import com.newbee.service.MainServiceTask;
import com.newbee.service.TaskType;
import com.newbee.sound.Sound;
import com.newbee.util.MD5Util;
import com.newbee.util.StringUtil;
import com.newbee.viewpager.RegViewPager;

public class MultChatFragement extends Fragment implements OnClickListener,
		OnRefrushActivity
{
	private int MSG_PALY_DLG = 1;
	// public static final String TAG = "TAG";

	public static final String INIT_STATE = "INIT_STATE";
	public static final String CHAT_ROOM_MAME = "CHAT_ROOM_MAME";
	public static final String USERS_LIST = "USERS_LIST";

	private String mRoomName;// 这个地方是没有@conference.wch-pc的
	public static final String JSON_KEY_DUR = "dur";
	public static final String JSON_KEY_MSG = "msg";

	public static final String JSON_KEY_TYPE = "type";

	public static final String TYPE_NORMAL = "0";//
	public static final String TYPE_HASE_LUYIN = "1";// 有人正在录音是发送的消息
	public static final String TYPE_END_LUYIN = "2";// 有人已经录完音了

	public static final String TYPE_END_SESSION = "3";// 整个的会话全不完成时候发送的消息

	private int mTime;
	/** *************************************** */

	private View mBtnBack;

	// private RelativeLayout mBottom;
	private ListView mListView;
	private ChatMsgViewAdapter mAdapter;
	private List<ChatMsgBean> mDataArrays = new ArrayList<ChatMsgBean>();

	// private boolean btn_vocie = false;
	private Handler mHandler = new Handler();

	private ImageButton trans_btn;

	private RegViewPager mViewPager;

	private List<View> mViewList;

	private TextView mSendInvate;

	private TextView mStartLuyin;

	private TextView mMultchatTime;

	private ArrayList<String> users;

	private int state;

	private View mSendOperate;
	private SpeexRecorder mSpeexRecorder;

	private String fileName;
	private PlayProgressDlg dlg;
	private Button mSend;
	private Button mCancle;

	private TextView mtitleMsg;
	private View Root;

	public static final String MASTER_TAG = "MASTER_TAG";

	private boolean isMaster;
	private static final int EX = 20;

	private Switch lang;

	public static final int CN = 0;
	public static final int EN = 1;

	private int langType = CN;

	private Handler playHandler = new Handler()
	{

		@Override
		public void handleMessage(Message msg)
		{
			if (msg.what == MSG_PALY_DLG)
			{
				dlg.hide();
			}
		}

	};

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
	{

		Root = inflater.inflate(R.layout.chat, container, false);

		// 启动activity时不自动弹出软键盘
		MainService.addActivityMap(MultChatFragement.class.getName(), this);
		this.getActivity()
				.getWindow()
				.setSoftInputMode(
						WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		initParas();

		initView();

		initViewPager();

		mViewPager.setCanScroll(isMaster);// 设置是否可以来回滚动
		if (isMaster)
		{
			// do nothing
		}
		else
		{
			trans_btn.setVisibility(View.GONE);// 将转换按钮去掉
		}

		dlg = PlayProgressDlg.createDialog(this.getActivity());
		dlg.setCancelable(false);
		dlg.setMessage("正在播放录音 ");

		return Root;

	}

	private Runnable updateTime = new Runnable()
	{

		@Override
		public void run()
		{
			MultChatFragement.this.mTime++;
			StringBuffer sb = new StringBuffer("");
			int h = MultChatFragement.this.mTime / 3600;
			if (h < 10)
			{
				sb.append("0" + h);
			}
			else
			{
				sb.append(h);
			}
			sb.append(":");
			int m = (MultChatFragement.this.mTime % 3600) / 60;
			if (m < 10)
			{
				sb.append("0" + m);
			}
			else
			{
				sb.append(m);
			}
			sb.append(":");
			int s = (MultChatFragement.this.mTime % 3600) % 60;
			if (s < 10)
			{
				sb.append("0" + s);
			}
			else
			{
				sb.append(s);
			}
			MultChatFragement.this.mMultchatTime.setText(sb.toString());
			MultChatFragement.this.mHandler.postDelayed(updateTime, 1000);
		}
	};

	private void initViewPager()
	{
		mViewList = new ArrayList<View>();
		this.mViewPager = (RegViewPager) Root.findViewById(R.id.viewpager);

		View invateView = LayoutInflater.from(this.getActivity()).inflate(
				R.layout.mult_chat_option_invate, null);

		this.mSendInvate = (TextView) invateView
				.findViewById(R.id.btn_sendInvate);
		this.mSendInvate.setOnClickListener(this);

		View luyinView = LayoutInflater.from(this.getActivity()).inflate(
				R.layout.mult_chat_option_luyin, null);

		lang = (Switch) luyinView.findViewById(R.id.open);

		lang.setOnCheckedChangeListener(new OnCheckedChangeListener()
		{

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean s)
			{

				if (s)
				{
					Toast.makeText(MultChatFragement.this.getActivity(),
							"您正在使用英文引擎进行转换", Toast.LENGTH_LONG).show();
					langType = EN;
				}
				else
				{
					Toast.makeText(MultChatFragement.this.getActivity(),
							"您正在使用中文的引擎进行转换", Toast.LENGTH_LONG).show();
					langType = CN;
				}
			}
		});
		this.mStartLuyin = (TextView) luyinView
				.findViewById(R.id.btn_start_luyin);
		this.mStartLuyin.setOnClickListener(this);
		this.mMultchatTime = (TextView) luyinView
				.findViewById(R.id.multchat_time);
		mViewList.add(invateView);
		mViewList.add(luyinView);
		mViewPager.setAdapter(new PagerAdapter()
		{

			@Override
			public boolean isViewFromObject(View arg0, Object arg1)
			{
				// TODO Auto-generated method stub
				return arg0 == arg1;
			}

			@Override
			public int getCount()
			{
				return mViewList.size();
			}

			@Override
			public void destroyItem(ViewGroup container, int position,
					Object object)
			{
				container.removeView((View) object);
			}

			@Override
			public Object instantiateItem(ViewGroup container, int position)
			{
				container.addView(mViewList.get(position));
				return mViewList.get(position);
			}

			@Override
			public int getItemPosition(Object object)
			{
				return POSITION_NONE;
			}
		});

		if (state == 2)
		{
			mViewPager.setCurrentItem(1);
		}

	}

	private void initParas()
	{
		Bundle bundle = this.getActivity().getIntent().getExtras();
		mRoomName = (String) bundle.get(CHAT_ROOM_MAME);
		// Toast.makeText(this.getActivity(), mRoomName,
		// Toast.LENGTH_LONG).show();
		users = bundle.getStringArrayList(USERS_LIST);
		state = bundle.getInt(INIT_STATE, 1);
		isMaster = bundle.getBoolean(MASTER_TAG, true);

	}

	public void initView()
	{
		trans_btn = (ImageButton) Root.findViewById(R.id.trans_btn);
		trans_btn.setOnClickListener(this);

		mListView = (ListView) Root.findViewById(R.id.listview);

		mBtnBack = (View) Root.findViewById(R.id.btn_multchat_back);
		mBtnBack.setOnClickListener(this);

		// rcChat_popup = this.findViewById(R.id.rcChat_popup);
		mSendOperate = Root.findViewById(R.id.mult_chat_operate);
		mSendOperate.setVisibility(View.GONE);
		mSend = (Button) Root.findViewById(R.id.voice_send);
		mSend.setOnClickListener(this);
		mCancle = (Button) Root.findViewById(R.id.voice_cancle);
		mCancle.setOnClickListener(this);

		mtitleMsg = (TextView) Root.findViewById(R.id.title_msg);

	}

	public void sendMsg(String type)
	{
		Map<String, Object> paras = new HashMap<String, Object>();
		paras.put(MainServiceKey.MULT_CHAT_ROOM_NAME, this.mRoomName);
		paras.put(MainServiceKey.MULT_DUR, mTime);
		paras.put(MainServiceKey.MULT_FILE_VOICE, fileName);
		paras.put(MainServiceKey.MSG_TYPE, type);
		paras.put(MainServiceKey.LANG_TYPE, langType);
		MainServiceTask mst = new MainServiceTask(TaskType.MULT_SEND_MSG,
				paras, MultChatFragement.class.getName());
		MainService.addActivityMap(MultChatFragement.class.getName(), this);
		MainService.addTaskQueue(mst);
	}

	public void onClick(View v)
	{
		// TODO Auto-generated method stub

		switch (v.getId())
		{

		case R.id.btn_sendInvate:
		{

			if (state == 1)
			{
				Map<String, Object> paras = new HashMap<String, Object>();

				paras.put(MainServiceKey.MULT_CHAT_ROOM_NAME, this.mRoomName);// 纯md5

				paras.put(MainServiceKey.MULT_CHAT_USERS, users);
				MainServiceTask mst = new MainServiceTask(
						TaskType.INVATE_FRIEND, paras,
						MultChatFragement.class.getName());
				MainService.addActivityMap(MultChatFragement.class.getName(),
						this);
				MainService.addTaskQueue(mst);
			}
			else if (state == 2 && state != EX)
			{

				sendMsg(TYPE_END_SESSION);
				state = EX;// 一个额外的状态
				mSendInvate.setText("完全结束");
				mSendInvate
						.setBackgroundResource(R.drawable.bg_multchat_luyin_black_btn);
				mSendInvate.setEnabled(false);
				// mMultchatTime.setTextColor(this.getResources().getColor(R.color.black));

			}
			break;
		}
		case R.id.btn_start_luyin:
		{

			if (state == 2 && state != EX)
			{
				sendMsg(TYPE_HASE_LUYIN);
				// 开始录音
				mTime = 0;
				fileName = MD5Util.getUnique() + ".spx";
				mSpeexRecorder = new SpeexRecorder(fileName);
				Thread th = new Thread(mSpeexRecorder);
				th.start();
				mSpeexRecorder.setRecording(true);
				this.mHandler.postDelayed(updateTime, 1000);// 更新时间
				mStartLuyin.setText("结束");
				mStartLuyin
						.setBackgroundResource(R.drawable.bg_multchat_luyin_stop_btn);

				state = 3;
			}
			else if (state == 3)
			{
				sendMsg(TYPE_END_LUYIN);
				// 结束录音
				mSpeexRecorder.setRecording(false);
				mStartLuyin.setText("播放");
				mStartLuyin
						.setBackgroundResource(R.drawable.bg_multchat_luyin_play_btn);
				mSendOperate.setVisibility(View.VISIBLE);
				this.mHandler.removeCallbacks(updateTime);

				state = 4;
			}
			else if (state == 4)
			{
				new SpeexPlayer(Sound.DIR + fileName).startPlay();
				dlg.show();
				Message msg = new Message();
				msg.what = MSG_PALY_DLG;
				playHandler.sendMessageDelayed(msg, mTime * 1000);
			}
			break;
		}

		case R.id.btn_multchat_back:
		{
			this.getActivity().finish();
			break;
		}

		case R.id.voice_cancle:
		{

			state = 2;
			mStartLuyin.setText("开始");
			mStartLuyin
					.setBackgroundResource(R.drawable.bg_multchat_luyin_start_btn);
			mSendOperate.setVisibility(View.GONE);
			this.mMultchatTime.setText("00:00:00");
			mTime = 0;

			break;
		}
		case R.id.voice_send:
		{
			sendMsg(TYPE_NORMAL);
			state = 2;
			mStartLuyin.setText("开始");
			mStartLuyin
					.setBackgroundResource(R.drawable.bg_multchat_luyin_start_btn);
			mSendOperate.setVisibility(View.GONE);
			this.mMultchatTime.setText("00:00:00");
			mTime = 0;

			break;

		}
		case R.id.trans_btn:
		{

			MultChatActivity mca = (MultChatActivity) this.getActivity();
			mca.goToNextPager(1);

			break;
		}
		default:
			break;
		}
	}

	@Override
	public void onDestroy()
	{
		sendMsg(TYPE_END_SESSION);
		MainService.removeActivity(MultChatFragement.class.getName());

		super.onDestroy();
	}

	@Override
	public void init()
	{
		// TODO Auto-generated method stub

	}

	@Override
	public RtInfo refresh(int taskID, Object... paras)
	{
		RtInfo rt = new RtInfo();
		rt.tag = false;
		switch (taskID)
		{
		case TaskType.MULT_CHAT_MSG:
		{

			String roomName = (String) paras[0];
			String from = (String) paras[1];
			String body = (String) paras[2];
			boolean isFrom = (Boolean) paras[3];
			String date = (String) paras[4];

			String mesType = null;
			/**
			 * 是本多人协同录音的窗口时，对录音的进行处理否则抛弃不予处理
			 */
			if (mRoomName.startsWith(roomName))
			{
				rt.tag = true;
				String Dur = null;
				String Msg = null;
				try
				{
					JSONObject json = new JSONObject(body);

					Dur = json.getString(JSON_KEY_DUR);
					Msg = json.getString(JSON_KEY_MSG);
					mesType = json.getString(JSON_KEY_TYPE);
					if (mesType.equals(TYPE_NORMAL))
					{
						ChatMsgBean entity = new ChatMsgBean();
						entity.setDate(date);

						String[] array = StringUtil.fromFormat(from);
						entity.setUserName(array[3].split("/")[1]);
						entity.setName(array[4]);
						entity.setMsgType(isFrom);// 设置来去不对
						entity.setTime(Dur + "\"");// "是为了显示的效果有两个小丿
						entity.setText(Msg);// 当名称中包含.amr后缀时，会自动对应到音频的视图
											// 否则为普通聊天视图
						// entity.setHead(array[5].substring(0, 1));
						entity.setHead(array[5].split("@")[0]);
						mDataArrays.add(entity);
						if (mAdapter == null)
						{
							mAdapter = new ChatMsgViewAdapter(
									this.getActivity(), mDataArrays);
							mListView.setAdapter(mAdapter);
						}
						else
						{
							mAdapter.notifyDataSetChanged();
						}
						mListView.setSelection(mListView.getCount() - 1);
					}
					else if (mesType.equals(TYPE_HASE_LUYIN))
					{
						if (isFrom)
						{
							mtitleMsg.setText("有朋友正在录音，您目前不能录音");
							mStartLuyin
									.setBackgroundResource(R.drawable.bg_multchat_luyin_black_btn);
							mStartLuyin.setEnabled(false);
							mMultchatTime.setTextColor(this.getResources()
									.getColor(R.color.black));
							if (mSpeexRecorder != null)
							{
								mSpeexRecorder.setRecording(false);
							}
						}
						else
						{
							mtitleMsg.setText("您正在录音中……");
						}

					}
					else if (mesType.equals(TYPE_END_LUYIN))
					{
						if (isFrom)
						{
							mtitleMsg.setText("当前没有人在录音，您可以录音");
							mStartLuyin
									.setBackgroundResource(R.drawable.bg_multchat_luyin_start_btn);
							mStartLuyin.setEnabled(true);
							mMultchatTime.setTextColor(this.getResources()
									.getColor(R.color.steelblue));
						}
						else
						{
							mtitleMsg.setText("您可以操作录音文件");
						}
					}
					else if (mesType.equals(TYPE_END_SESSION))
					{
						mStartLuyin
								.setBackgroundResource(R.drawable.bg_multchat_luyin_black_btn);
						mtitleMsg.setText("本次会话已经完全结束，不可再录音");
						mStartLuyin.setEnabled(false);
						if (mSpeexRecorder != null)
						{
							mSpeexRecorder.setRecording(false);
						}
						mMultchatTime.setTextColor(this.getResources()
								.getColor(R.color.black));
						state = EX;
					}

				}
				catch (JSONException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			else
			{
				break;
			}
			break;
		}

		case TaskType.INVATE_FRIEND:
		{

			boolean re = (Boolean) paras[0];

			if (re)
			{

				this.mViewPager.setCurrentItem(1);
				state = 2;
				this.mSendInvate.setText("停止群录");
				this.mSendInvate
						.setBackgroundResource(R.drawable.bg_multchat_invate_stop_btn);
			}
			else
			{
				Toast.makeText(this.getActivity(), "邀请朋友出现问题",
						Toast.LENGTH_LONG).show();
			}

			break;
		}

		default:
			break;
		}
		return rt;

	}

	@Override
	public void onDestroyView()
	{
		// TODO Auto-generated method stub
		if (mAdapter != null)
		{
			mAdapter.dismissDlg();
		}
		super.onDestroyView();
	}
}